package com.fick.struts.action;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.fick.hibernate.dao.AdminDAO;
import com.fick.hibernate.dao.AdminQxDAO;
import com.fick.hibernate.dao.ChannelDAO;
import com.fick.hibernate.dao.RoleDAO;
import com.fick.hibernate.dao.SyslogDAO;
import com.fick.hibernate.model.Admin;
import com.fick.hibernate.model.AdminQx;
import com.fick.hibernate.model.Role;
import com.fick.hibernate.model.Syslog;
import com.fick.struts.form.LoginForm;
import com.fick.tools.SystemLogger;
import com.fick.util.DES;

public class LoginAction extends DispatchAction {

	private static final Log log = LogFactory.getLog(LoginAction.class);

	public ActionForward addAdmin(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		LoginForm lf = (LoginForm) form;
		// 打印出
		SystemLogger.operatelog(request, "添加用户");
		try {
			Admin admin = new Admin();
			AdminDAO adminDao = new AdminDAO();
			if (adminDao.findByProperty("adminName", lf.getUserName()).size() > 0) {
				request.getSession().setAttribute("message", "用户名已存在");
				return mapping.findForward("addUser");
			} else {

				admin.setAdminName(lf.getUserName());
				try {
					admin.setAdminPass(DES.encrypt(lf.getUserPass().getBytes()));
				} catch (Exception e1) {
					e1.printStackTrace();
				}

				admin.setIsAss(lf.getIsAss());
				admin.setUnit(request.getParameter("unit")); // 所属单位
				admin.setUserOrder(Integer.parseInt(request.getParameter("userOrder"))); // 序号
				admin.setFullName(request.getParameter("fullName")); // 全名
				try {
					Role role = new RoleDAO().findById(Integer.parseInt(request.getParameter("role")));
					admin.setRole(role);
				} catch (Exception e) {
				}
				adminDao.save(admin);
				SystemLogger.operatelog(request, "添加用户成功");
				request.getSession().setAttribute("message", "添加用户成功");

			}
			return mapping.findForward("managerUser");
		} catch (RuntimeException re) {
			re.printStackTrace();
			log.error(re);
			SystemLogger.operatelog(request, "添加管理用户失败");
		}
		return null;
	}

	// 添加用户权限
	public ActionForward addAdminQx(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {

		String myids[] = request.getParameterValues("qxs"); // 频道id
		String userid = request.getParameter("userid");

		AdminDAO dao = new AdminDAO();
		Admin admin = dao.findById(Integer.parseInt(userid));

		AdminQxDAO qxdao = new AdminQxDAO();

		qxdao.delByHql("delete from AdminQx where admin.adminId = " + Integer.parseInt(userid));// 修改权限前删除所有关于此用户的权限

		try {
			for (int i = 0; i < myids.length; i++)// 对每个操作权限进行分类添加
			{
				AdminQx qx = new AdminQx();
				qx.setChannel(new ChannelDAO().findById(Integer.valueOf(myids[i])));
				qx.setAdmin(admin);
				qxdao.save(qx);
			}
		} catch (NullPointerException e) {
			return mapping.findForward("managerUserqx");
		}
		return mapping.findForward("managerUserqx");
	}

	public ActionForward adminlogin(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		// 定义列表名
		List li = new ArrayList();
		// 得到Form
		LoginForm lf = (LoginForm) form;

		if (request.getParameter("qtdl") != null) {
			try {
				AdminDAO adminDao = new AdminDAO();
				Admin admin = new Admin();
				li = adminDao.getSession().createQuery("from Admin where adminName = '" + lf.getUserName() + "'").list();
				if (li.size() > 0) {
					admin = (Admin) li.get(0);

					// FIXME 忘了密码修改这里，生产时，修改这里
					if (!lf.getUserPass().equals(new String(DES.decrypt(admin.getAdminPass())))) {
						// if (1 == 2) {
						request.getSession().setAttribute("message", "用户名或密码错误");
						return mapping.findForward("errorPage");
					} else {

						request.getSession().setAttribute("admin", admin);

						SyslogDAO slDAO = new SyslogDAO();
						Syslog sl = new Syslog();
						String ip = request.getRemoteAddr();
						String logname = admin.getAdminName();
						sl.setIp(ip);
						sl.setOperator(logname);
						sl.setOpertime(new Date());
						slDAO.save(sl);

						return mapping.findForward("success");
					}
				} else {
					request.getSession().setAttribute("message", "用户不存在，请联系管理员！");
					return mapping.findForward("errorPage");
				}

			} catch (Exception e) {
				request.getSession().setAttribute("message", e.getMessage());
				e.printStackTrace();
				log.error(e);
			}
		} else {
			request.getSession().setAttribute("message", "验证码错误");
			return mapping.findForward("errorPage");
		}
		return null;
	}

	public ActionForward adminQuit(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		SystemLogger.operatelog(request, "管理员退出");
		request.getSession().removeAttribute("admin");
		SystemLogger.operatelog(request, "管理退出成功");
		return mapping.findForward("errorPage");
	}

	public ActionForward adminUp(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		// 得到form表单
		LoginForm lf = (LoginForm) form;
		// 系统打印类
		SystemLogger.operatelog(request, "管理员修改");
		try {
			AdminDAO adminDao = new AdminDAO();
			Admin admin = (Admin) adminDao.findById(lf.getAdminId());
			if (!lf.getUserName().trim().equals(admin.getAdminName().trim())
					&& adminDao.findByProperty("adminName", lf.getUserName()).size() > 0) {
				request.getSession().setAttribute("message", "用户名已存在");
				return mapping.findForward("managerUser");
			} else {
				admin.setAdminName(lf.getUserName());
				try {
					admin.setAdminPass(DES.encrypt(lf.getUserPass().getBytes()));
				} catch (Exception e1) {
					e1.printStackTrace();
				}

				admin.setIsAss(lf.getIsAss());
				admin.setUnit(request.getParameter("unit")); // 所属单位
				admin.setUserOrder(Integer.parseInt(request.getParameter("userOrder"))); // 序号
				admin.setFullName(request.getParameter("fullName")); // 序号
				try {
					Role role = new RoleDAO().findById(Integer.parseInt(request.getParameter("role")));
					admin.setRole(role);
				} catch (Exception e) {
				}
				// 修该Admin
				adminDao.update(admin);
				// 写入新的Session
				request.getSession().setAttribute("message", "管理员修改成功");
				SystemLogger.operatelog(request, "管理员修改成功");
				return mapping.findForward("managerUser");
			}
		} catch (RuntimeException re) {
			re.printStackTrace();
			log.error(re);
			SystemLogger.operatelog(request, "管理员修改失败");
		}
		return null;
	}

	// 删除用户权限
	public ActionForward clearQx(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		String userid = request.getParameter("userid");
		try {
			AdminQxDAO qxdao = new AdminQxDAO();
			qxdao.delByHql("delete from AdminQx where admin.adminId = " + userid);// 修改权限前删除所有关于此用户的权限
			request.setAttribute("message", "清空权限成功");
			response.sendRedirect(request.getContextPath() + "/admin/managerUserQx.jsp?userid=" + userid);
		} catch (Exception e) {

		}
		return null;
	}

	public ActionForward delAdmin(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {

		AdminDAO adminDao = new AdminDAO();
		Admin admin = new Admin();
		try {
			SystemLogger.operatelog(request, "删除管理员");
			int adminId = Integer.parseInt(request.getParameter("adminId"));
			admin = adminDao.findById(adminId);
			adminDao.delete(admin);
			SystemLogger.operatelog(request, "删除用户成功");
			request.getSession().setAttribute("message", "删除用户成功");
			return mapping.findForward("managerUser");
		} catch (RuntimeException re) {
			re.printStackTrace();
			log.error(re);
			SystemLogger.operatelog(request, "删除用户失败");
		}
		return null;
	}

	// (信息添加树)动态加载树 二级目录 add by wangning
	public ActionForward getBig(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/xml");
			String typeid = request.getParameter("typeid");
			String userid = request.getParameter("userid");

			StringBuffer temp = new StringBuffer();
			temp.append("<?xml  version=\"1.0\" encoding=\"UTF-8\" ?><tree>");
			/*
			 * Type type = new TypeDAO().findById(Integer.valueOf(typeid));
			 * BigclassDAO bgdao = new BigclassDAO(); SmallclassDAO smdao = new
			 * SmallclassDAO(); List<Bigclass> biglist = (List)new
			 * BigclassDAO().findByProperty("type",type); Bigclass big = new
			 * Bigclass(); for(int i = 0 ; i < biglist.size();i++){ big =
			 * (Bigclass)biglist.get(i); int size = smdao.findByProperty("bigclass",
			 * big).size(); if(size>0) {
			 * temp.append(" <tree text=\""+big.getBigclassName
			 * ()+"\" src=\""+request.getContextPath
			 * ()+"/admin/login.do?method=getSm&amp;bigid="
			 * +big.getBigclassId()+"&amp;userid="
			 * +userid+"\" value=\"bigid"+big.getBigclassId()+"\" type=\"check\" />");
			 * } else {
			 * temp.append(" <tree text=\""+big.getBigclassName()+"\" value=\"bigid"
			 * +big.getBigclassId()+"\" type=\"check\" />"); } }
			 */

			temp.append("</tree>");
			response.getWriter().write(temp.toString());

		} catch (Exception e) {
			log.info(e);
		}
		return null;
	}

	// 报价大分类权限
	public ActionForward getBjbig(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {

		try {
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/xml");
			// String typeid = request.getParameter("typeid");
			String userid = request.getParameter("userid");

			StringBuffer temp = new StringBuffer();
			temp.append("<?xml  version=\"1.0\" encoding=\"UTF-8\" ?><tree>");
			/*
			 * Type type = new TypeDAO().findById(11); BigclassDAO bgdao = new
			 * BigclassDAO(); SmallclassDAO smdao = new SmallclassDAO();
			 * List<Bigclass> biglist = (List)new
			 * BigclassDAO().findByProperty("type",type); Bigclass big = new
			 * Bigclass(); for(int i = 0 ; i < biglist.size();i++){ big =
			 * (Bigclass)biglist.get(i); int size = smdao.findByProperty("bigclass",
			 * big).size(); if(size>0) {
			 * temp.append(" <tree text=\""+big.getBigclassName
			 * ()+"\" src=\""+request.getContextPath
			 * ()+"/admin/login.do?method=getSm&amp;bigid="
			 * +big.getBigclassId()+"&amp;userid="
			 * +userid+"\" value=\"bigid"+big.getBigclassId()+"\" type=\"check\" />");
			 * } else {
			 * temp.append(" <tree text=\""+big.getBigclassName()+"\" value=\"bigid"
			 * +big.getBigclassId()+"\" type=\"check\" />"); } }
			 */
			temp.append("</tree>");
			response.getWriter().write(temp.toString());

		} catch (Exception e) {
			log.info(e);
		}
		return null;
	}

	// (信息添加树)动态加载树 三级目录 add by wangning
	public ActionForward getSm(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/xml");
			String bigid = request.getParameter("bigid");
			String userid = request.getParameter("userid");

			StringBuffer temp = new StringBuffer();
			temp.append("<?xml  version=\"1.0\" encoding=\"UTF-8\" ?><tree>");

			/*
			 * BigclassDAO bgdao = new BigclassDAO(); Smallclass sm = new
			 * Smallclass(); Bigclass big = bgdao.findById(Integer.valueOf(bigid));
			 * SmallclassDAO smdao = new SmallclassDAO(); List<Smallclass> smlist =
			 * (List)new SmallclassDAO().findByProperty("bigclass",big); for(int i = 0
			 * ; i < smlist.size();i++){ sm = (Smallclass)smlist.get(i);
			 * 
			 * temp.append(" <tree text=\""+sm.getSmallclassName()+"\" value=\"smid"+sm
			 * .getSmallclassId()+"\" type=\"check\" />"); }
			 * 
			 * temp.append("</tree>"); response.getWriter().write(temp.toString());
			 */

		} catch (Exception e) {
			log.info(e);
		}
		return null;
	}

	// (信息添加树)动态加载树 首级目录 add by wangning
	public ActionForward getType(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/xml");
			StringBuffer temp = new StringBuffer();
			String userid = request.getParameter("userid");

			temp.append("<?xml  version=\"1.0\" encoding=\"UTF-8\" ?><tree>");
			/*
			 * Type type = new Type(); BigclassDAO bgdao = new BigclassDAO();
			 * List<Type> typelist = (List)new TypeDAO().findAll(); for(int i = 0 ; i
			 * < typelist.size();i++){ type = (Type)typelist.get(i); int size =
			 * bgdao.findByProperty("type", type).size();
			 * 
			 * if(size>0) {
			 * temp.append(" <tree text=\""+type.getTypeName()+"\" src=\""
			 * +request.getContextPath
			 * ()+"/admin/login.do?method=getBig&amp;typeid="+type
			 * .getTypeid()+"&amp;userid="
			 * +userid+"\" value=\"typeid"+type.getTypeid()+"\" type=\"check\" />"); }
			 * else {
			 * temp.append(" <tree text=\""+type.getTypeName()+"\" value=\"typeid"
			 * +type.getTypeid()+"\" type=\"check\" />"); } }
			 */

			temp.append("</tree>");
			response.getWriter().write(temp.toString());

		} catch (Exception e) {
			log.info(e);
		}
		return null;
	}

	// 验证是否有此用户
	public ActionForward nameUniqueValid(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {

		String userName = request.getParameter("userName");
		try {
			request.setCharacterEncoding("UTF-8");
			response.setContentType("text/xml; charset=UTF-8");
			response.setHeader("Cache-Control", "no-cache");
			PrintWriter out = response.getWriter();
			AdminDAO adminDAO = new AdminDAO();
			Admin admin = new Admin();
			String name = "";
			if (request.getParameter("adminId") != null && request.getParameter("adminId").trim().length() > 0) {
				admin = adminDAO.findById(Integer.parseInt(request.getParameter("adminId")));
				if (admin != null) {
					name = admin.getAdminName();
				}
			}
			if (!name.equals(userName) && adminDAO.findByProperty("adminName", userName).size() > 0) {
				out.println("该用户名已被注册!");
				out.close();
			} else {
				out.println("该用户名可用!");
				out.close();
			}
		} catch (Exception e) {
		}

		return null;
	}

	// 密码设置
	public ActionForward pass(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			Admin admin = (Admin) request.getSession().getAttribute("admin");
			String oldpass = request.getParameter("oldpass");
			String newPass = request.getParameter("newpass");

			// FIXME 忘了密码修改这里，生产时，修改这里
			String dd = new String(DES.decrypt(admin.getAdminPass()));
			if (oldpass != null && !oldpass.trim().equals(dd)) {
				// if (1 == 2) {
				request.setAttribute("info", "原密码不正确!");
			} else {
				AdminDAO adminDAO = new AdminDAO();
				Admin admin2 = adminDAO.findById(admin.getAdminId());
				if (admin2 != null) {
					admin2.setAdminPass(DES.encrypt(newPass.getBytes()));
					adminDAO.update(admin2);
				}
				request.setAttribute("info", "修改成功!");
			}
		} catch (Exception e) {
			request.setAttribute("info", e.getMessage());
			log.info(e);
		}
		return mapping.findForward("pass");
	}
}